package com.apkcore.core

import android.app.Application
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.ViewModelStore
import androidx.lifecycle.ViewModelStoreOwner

//class App2 : Application(), ViewModelStoreOwner {
//    private lateinit var mAppViewModelStore: ViewModelStore
//
//    private var mFactory: ViewModelProvider.Factory? = null
//    override val viewModelStore: ViewModelStore = mAppViewModelStore
//
//    override fun onCreate() {
//        super.onCreate()
//        instance = this
//        mAppViewModelStore = ViewModelStore()
//        appViewModelInstance = getAppViewModelProvider()[AppViewModel::class.java]
//    }
//
//    private fun getAppViewModelProvider(): ViewModelProvider {
//        return ViewModelProvider(this, this.getAppFactory())
//    }
//
//    private fun getAppFactory(): ViewModelProvider.Factory {
//        if (mFactory == null) {
//            mFactory = ViewModelProvider.AndroidViewModelFactory.getInstance(this)
//        }
//        return mFactory as ViewModelProvider.Factory
//    }
//
//    companion object {
//        lateinit var instance: App2
//        lateinit var appViewModelInstance: AppViewModel
//    }
//}
/**
 * application使用viewmodel
 * 使用：val appViewModel: AppViewModel by lazy { getAppViewModel() }
 */
class AppScopeViewModelProvider private constructor(private val application: Application) :
    ViewModelStoreOwner {

    private val eventViewModelStore: ViewModelStore = ViewModelStore()

    override val viewModelStore: ViewModelStore
        get() = eventViewModelStore

    private val mApplicationProvider: ViewModelProvider by lazy {
        ViewModelProvider(
            this,
            ViewModelProvider.AndroidViewModelFactory.getInstance(application)
        )
    }

    fun <T : ViewModel> getApplicationScopeViewModel(modelClass: Class<T>): T {
        return mApplicationProvider[modelClass]
    }

    companion object {
        @Volatile
        private var instance: AppScopeViewModelProvider? = null

        fun getInstance(application: Application): AppScopeViewModelProvider {
            return instance ?: synchronized(this) {
                instance ?: AppScopeViewModelProvider(application).also { instance = it }
            }
        }
    }
}

//定义扩展方法
inline fun <reified VM : ViewModel> Application.getAppViewModel(): VM {
    return AppScopeViewModelProvider.getInstance(this)
        .getApplicationScopeViewModel(VM::class.java)
}

//定义扩展方法
inline fun <reified VM : ViewModel> Any.getAppViewModel(application: Application): VM {
    return AppScopeViewModelProvider.getInstance(application)
        .getApplicationScopeViewModel(VM::class.java)
}